import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Book } from './entities/book.entity';
import { Repository, SelectQueryBuilder } from 'typeorm';
import { getPageResult } from 'src/utils';

@Injectable()
export class BooksService {
  constructor(
    @InjectRepository(Book)
    private bookRepository: Repository<Book>
  ) {
    // 不指定关系是使用以下方式
    // this.selectQueryBuild = this.bookRepository.createQueryBuilder('b')
    // .leftJoinAndSelect(Category, 'c', 'b.category_id = c.id')
    // .select('c.*,b.*')
  }
  // 新增图书
  async create(createBookDto: CreateBookDto) {
    return await this.bookRepository.insert(createBookDto)
  }
  // 分页查询所有图书
  async findAll({pageIndex, pageSize, book_name}) {
    let queryBuilder: SelectQueryBuilder<Book> = this.bookRepository.createQueryBuilder('b')
    .leftJoinAndSelect('b.category_id', 'c')
    .select('c.*,b.*');
    if(book_name) {
      queryBuilder = queryBuilder
      .where('b.book_name LIKE :book_name', { book_name: `%${book_name}%`})
    }
    return await getPageResult(pageIndex, pageSize, queryBuilder)
  }
  // 获取图书详情
  async findOne(id: number) {
    return await this.bookRepository.createQueryBuilder('b')
    .leftJoinAndSelect('b.category_id', 'c')
    .select('c.category_name,b.*')
    .where({ id: id})
    .getRawOne()
  }
  // 修改图书信息
  async update(id: number, updateBookDto: UpdateBookDto) {
    const isExist = await this.bookRepository.findOne({where: {id}})
    if (isExist) {
      return await this.bookRepository.update(id, updateBookDto)
    } else {
      throw new HttpException({message: `修改图书信息失败，图书编号${id}的图书不存在` }, HttpStatus.OK)
    }
  }
  // 删除图书
  async remove(id: number) {
    return await this.bookRepository.softDelete(id)
  }
}
